package com.egg.common.mybatis.util;

import cn.hutool.core.util.ObjectUtil;
import com.egg.common.context.util.LocalThreadContextUtils;

import java.util.Optional;

/**
 * 分页工具类
 *
 * @author ruoyi
 */
public class DataScopeUtils {

    /**
     * 权限控制表
     * -- 如果在不同物理机中的数据库, mysql 需要做 federated 映射, 然后通过映射表做关联以做到数据权限控制
     */
    private static final String dataScopeTableName = "auth_dept_link_user";

    /**
     * 构建数据权限的sql
     * 拼接sql示例
     * (SELECT 1 FROM auth_dept_link_user
     * WHERE auth_dept_link_user.user_id = test.creator
     * AND (auth_dept_link_user.user_id IN (1) OR auth_dept_link_user.dept_id IN (1)))
     *
     * @param tableName 表名
     */
    public static Optional<String> buildDataScopeExistSql(String tableName) {
        if (ObjectUtil.isEmpty(tableName)) {
            return Optional.empty();
        }
        String dataPerm = LocalThreadContextUtils.getDataPerm();
        if (ObjectUtil.isEmpty(dataPerm)) {
            // 没有限制部门, 则直接放行, 会查询所有数据
            return Optional.empty();
        }
        String join = " SELECT 1 FROM " + dataScopeTableName + " WHERE " + dataScopeTableName + ".user_id = " + tableName + ".creator ";
        StringBuilder exists = new StringBuilder();
        exists.append("(");
        exists.append(join);
        String oneself = " AND (" + dataScopeTableName + ".user_id IN (" + LocalThreadContextUtils.getUserId() + ")";
        exists.append(oneself);
        String dept = " OR " + dataScopeTableName + ".dept_id IN ( %s ))";
        exists.append(String.format(dept, dataPerm));
        exists.append(")");
        return Optional.of(exists.toString());
    }


}